import axios from 'axios'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'



let api = process.env.VUE_APP_BASE_API; //重心请求的IP

//引入路由
import router from "@/router";
//element设施---

// 设置弹出框只能单个出现
const showMessage = Symbol("showMessage");

class DonMessage {
  success(options, single = true) {
    this[showMessage]("success", options, single);
  }
  warning(options, single = true) {
    this[showMessage]("warning", options, single);
  }
  info(options, single = true) {
    this[showMessage]("info", options, single);
  }
  error(options, single = true) {
    this[showMessage]("error", options, single);
  }

  [showMessage](type, options, single) {
    if (single) {
      if (document.getElementsByClassName("el-message").length === 0) {
        Message[type](options);
      }
    } else {
      Message[type](options);
    }
  }
}
var message = new DonMessage();
//element设施==========
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 2500 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['Access-Control-Allow-Origin'] = "*";

    // if (store.userInfo) {
    //    config.headers["Authorization"] = store.userInfo.adminToken ? store.userInfo.adminToken : '';
    // }
    // config.headers['dataType']= 'JSONP';
    // console.log(store.getters)
    //  console.log(store.getters.userInfo)
    //     console.log(store.state.userInfo)
    if (store.getters.token) {

      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    const res = response
    // console.log('store.getters', store.getters)
    // console.log('store.getters.userInfo', store.getters.userInfo)
    // console.log('store.state.userInfo', store.state.userInfo)
    //用户过期的两种情况A0230可以再获取,A0311只能登录
    if (response.data.status == 'A0230') {
      console.log('登录授权已过期的url', response.config.url);
      if (response.config.url = 'user/security/ref') {
        message.error('登录已过期');
        router.push({
          path: '/Login'
        });
        return;
      }
      axios.get(api + '/user/security/ref', {}).then(res2 => {
        console.log('重来===》', res2)
        var info = store.getters.info;
        info.auth_TOKEN = res2.data.data.auth_TOKEN;
        response.config.headers.Authorization = res2.data.data.auth_TOKEN;
        store.commit("UserState", info);
        //本来打算自动重新请求的,但返回的数据不会渲染,所以当TOKEN就位以后,我刷新页面了
        if (response.config.__retryCount > 0) {
          router.go(0);
        }
        //重新请求
        //axiosRetryInterceptor(response);
      });
    }

    if (response.data.status == 'A0311') {
      message.error('登录已过期');
      router.push({
        path: '/Login'
      });
    }
    if (res.status !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 100
      })
    } else {

      return res.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 100
    })
    return Promise.reject(error)
  }
)

//重新请求
function axiosRetryInterceptor(err) {
  var config = err.config;
  // 如果配置不存在或未设置重试选项，则拒绝
  if (!config || !config.retry) return Promise.reject(err);
  // 设置变量以跟踪重试次数
  config.__retryCount = config.__retryCount || 0;
  console.log('第', config.__retryCount, '重新获取数据的请求===》', config.url);
  // 检查我们是否已经注销了总重试次数
  if (config.__retryCount > config.retry) {
    return
    // 剔除错误
    //return Promise.reject(err);
  }
  axios.defaults.retry = 0;
  // 增加重试次数
  config.__retryCount += 1;
  // 创建新的异步对象来处理重试请求
  var backoff = new Promise(function(resolve) {
    setTimeout(function() {
      resolve();
    }, config.retryDelay || 1);
  });
  //返回调用AXIOS来重试请求
  return backoff.then(function() {
    return axios(config);
  });
}

export default service
